package com.app.controller;


import com.app.common.Result;
import com.app.common.SystemConfig;
import com.app.config.RedisService;
import com.app.model.UserModel;
import com.app.service.SystemConfigService;
import com.app.service.UserService;
import com.app.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@Controller
@RequestMapping("/ivTransform")
/**
 * 券 积分 相互转换的类
 */
public class IVTransform {



    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SystemConfigService systemConfigService;



    @GetMapping("/transformVToI")
    public Result transformVToI(Double v, @RequestParam(required = false) Double i, HttpServletRequest request) {
        Integer rate = getRate();
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
// 加锁，防止并发修改用户数据
        String lockKey = "user_lock_" + openId;
        Boolean expire = stringRedisTemplate.expire(lockKey, rate, TimeUnit.SECONDS);
        if (!expire) {
            stringRedisTemplate.opsForValue().set(lockKey, v + "," + i, 5, TimeUnit.SECONDS);
            try {
                UserModel userModel = userService.getUserByOpenid(openId);
                if (userModel == null) {
                    return Result.error(405, "用户不存在");
                }

                Double voucher = userModel.getVoucher();
                if (voucher<v || v<0){
                    return Result.error(400,"余额不足，不予转换");
                }
                Double i1 = v * rate;
                if (!i1.equals(i)){
                    return Result.error(400, "余额不足，不予转换");
                }
                Double integral = userModel.getIntegral();
                integral += i;
                voucher -= v;
                userModel.setIntegral(integral);
                userModel.setVoucher(voucher);
                userService.updateById(userModel);
                return Result.success(v + "的券成功转换成" + i + "的积分");
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(500, e.getMessage());
            }
        } else {
            // 获取锁失败，可能是其他线程正在修改用户数据，这里可以根据业务需求进行处理
            return Result.error(500, "服务器繁忙，请稍后重试");
        }
    }
    @GetMapping("/transformIToV")
    public Result transformIToV(Double v, Double i, HttpServletRequest request) {
        Integer rate = getRate();
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        // 加锁，防止并发修改用户数据
        String lockKey = "user_lock_" + openId;
        Boolean expire = stringRedisTemplate.expire(lockKey, rate, TimeUnit.SECONDS);
        if (!expire) {
            stringRedisTemplate.opsForValue().set(lockKey, v + "," + i, 5, TimeUnit.SECONDS);
            try {
                UserModel userModel = userService.getUserByOpenid(openId);
                if (userModel == null) {
                    return Result.error(405, "用户不存在");
                }
                Double integral = userModel.getIntegral();
                if (integral<i || i<0){
                    return Result.error(400,"积分不足，不予兑换");
                }
                Double v1 = integral/rate;
                if  (!v1.equals(v)) {
                    return Result.error(400, "积分不足，不予转换");
                }
                Double voucher = userModel.getVoucher();

                integral -= i;
                voucher += v;
                userModel.setIntegral(integral);
                userModel.setVoucher(voucher);
                userService.updateById(userModel);
                return Result.success(i + "个积分成功转换成" + v + "个劵");
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(500, e.getMessage());
            }
        } else {
            // 获取锁失败，可能是其他线程正在修改用户数据，这里可以根据业务需求进行处理
            return Result.error(500, "服务器繁忙，请稍后重试");
        }
    }




    public Integer getRate(){
        SystemConfig systemConfig = systemConfigService.getById(1);
        Integer rate = Integer.valueOf(systemConfig.getValue());
        return rate;
    }


}
